package v1

import (
	"errors"
	"net/http"
	"sweetsunnyflower/app/queues"
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/config"
	"sweetsunnyflower/pkg/jwt"
	"sweetsunnyflower/pkg/response"

	"sweetsunnyflower/pkg/logger"
	"sweetsunnyflower/pkg/wechat"

	"io"
	"sweetsunnyflower/app/models/user"

	"github.com/gin-gonic/gin"
	"github.com/spf13/cast"
)

type WechatsController struct {
	Controller
}

func (ctrl *WechatsController) OAuth2(c *gin.Context) {

	request := requests.WechatRequest{}
	if ok := requests.Validate(c, &request, requests.WechatCode); !ok {
		return
	}

	wechat := wechat.NewWechat()

	base, err := wechat.OfficialAccount.OAuth.UserFromCode(request.Code)

	if err != nil {
		response.Error(c, err)
		return
	}

	info, _ := wechat.OfficialAccount.OAuth.UserFromToken(base.GetAccessToken(), base.GetOpenID())

	// 查询用户是否存在
	userModel := user.GetByOpenId(info.GetOpenID())

	if userModel.ID == 0 {

		// 创建用户
		// 2. 验证成功，创建数据
		userModel = user.User{
			Name:     info.GetName(),
			Nickname: info.GetNickname(),
			OpenId:   info.GetOpenID(),
			Avatar:   info.GetAvatar(),
			Email:    info.GetEmail(),
			Phone:    info.GetMobile(),
		}
		userModel.Create()
	}
	logger.InfoString("controller", "OAuth2", cast.ToString(userModel.ID))
	if userModel.ID > 0 {

		queues.RegisgerEvent(userModel.ID)

		// token
		token := jwt.NewJWT().IssueToken(userModel.GetStringID(), userModel.Name)

		response.CreatedJSON(c, gin.H{
			"token": token,
			"data":  userModel,
		})

	} else {
		response.Abort500(c, "登录失败~")
	}
}

// 接受微信服务器推送消息
func (ctrl *WechatsController) Notify(c *gin.Context) {

	wechat := wechat.NewWechat()

	rs, err := wechat.OfficialAccount.Server.VerifyURL(c.Request)

	if err != nil {
		c.String(http.StatusOK, "error:%s", err)
	}

	text, _ := io.ReadAll(rs.Body)

	c.String(http.StatusOK, string(text))
}

func (ctrl *WechatsController) GetJSSDKConfig(c *gin.Context) {

	url := c.Query("url")

	if url == "" {
		response.Error(c, errors.New("url参数不能为空"))
		return
	}

	wechat := wechat.NewWechat()

	jsapiList := []string{"updateAppMessageShareData"}
	debug := config.GetBool("wechat.jssdk.debug")
	beta := config.GetBool("wechat.jssdk.beta")
	openTagList := []string{"wx-open-launch-app", "wx-open-launch-weapp"}

	buildConfig, err := wechat.OfficialAccount.JSSDK.BuildConfig(c, jsapiList, debug, beta, openTagList, url)
	if err != nil {
		response.Error(c, err)
		return
	}

	response.Data(c, buildConfig)
}
